<?php
namespace app\api\controller\orderhawa;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\common\model\company\Contract;
use app\common\model\orderhawa\HawaList;
use app\common\model\power\Rolepower;
use app\common\model\quotation\QuotationList;
use app\common\model\company\Company;
use app\common\model\user\User as UserModel;
use app\api\controller\Pub;
use think\facade\Env;
use think\File;

class Orderhawa extends Base
{
    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(101002);
    }

    /**
     * 获取报价类型
     * @return [type] [description]
     */
    public function gethawaquottype()
    {
        return myok(HAWAQUOT);
    }
    /**
     * 获取企业电话
     * @return [type] [description]
     */
    public function getcompanytel(){
        return myok(CELLPHONE);
    }

    /**
     * 删除订单
     * @return [type] [description]
     */
    public function deleteorderlist(){
        $id   = input('id');
        if(empty($id)){
            return myerr('缺少数据');
        }
        $data = HawaList::get($id);
        //判断是否为管理者
        if($data['UpUserId']!==Pub::userid()){
            return moerr('没有权限');
        }
        //判断订单状态
        if($data['State']>=HawaList::STATEWAITOK){
            return moerr('订单已有收集员负责无法删除，请与收集员沟通');
        }
        $data = HawaList::deleteorderlist($id);
        return myok('删除成功');
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    function list() {
        $data = input('get.');
        $data = init_where($data);
        $list = HawaList::usergetlist($data, 'hawa');
        foreach ($list['list'] as $key => $value) {
            if (empty($value['bussinfo']['UserName'])) {
                $list['list'][$key]['Name'] = '暂无';
            } else {
                $list['list'][$key]['Name'] = $value['bussinfo']['UserName'];
            }
        }
        $list['tr']['title'] = ['收集员', '下单时间', '订单状态', '查看'];
        $list['tr']['key']   = ['Name', 'UpTime', 'State', 'HawaListId'];
        return myok($list);
    }
    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getinfo()
    {
        $id = input('id');
        if (empty($id)) {
            return myerr('缺少参数，请重新尝试');
        }
        $data = HawaList::getinfo($id);
        if (!$data['code']) {
            return myerr($data['msg']);
        }
        $data              = $data['msg'];
        $data['CELLPHONE'] = CELLPHONE;
        return myok($data);
    }
    /**
     * 用户下单
     * @return [type] [description]
     */
    public function createorder()
    {
        $data = input('post.');
        //获取产品订单信息
        $data['goodlist']  = explode(',', $data['goodlist']);
        $data['valuelist'] = explode(',', $data['valuelist']);
        $data['Box']         = explode(',', $data['Box']);
        $data['BoxCount']    = explode(',', $data['BoxCount']);
        $data['GoodName']    = explode(',', $data['GoodName']);
        $data['ObjectState'] = explode(',', $data['ObjectState']);
        $data['Harmful'] = explode(',', $data['Harmful']);
        //删去为空的产品
        foreach ($data['valuelist'] as $key => $value) {
            if (empty($value)) {
                unset($data['goodlist'][$key]);
                unset($data['valuelist'][$key]);
            }
        }
        //获取报价信息
        if (HAWAQUOT == 'acco') {
            $quot = QuotationList::get_create_question($data);
            if (!$quot['code']) {
                return myerr($quot['msg']);
            }
            $data['quot'] = $quot['msg'];
        }
        //创建终端订单
        $hawa = HawaList::screate($data);
        if (!$hawa['code']) {
            return myerr($hawa['msg']);
        }
        $hawa = $hawa['msg'];
        $sb   = Sendmessage::Orderhawa(1, $hawa->HawaListId, $hawa->toArray());
        if (!$sb['code']) {
            return myok('下单成功，请联系公司。');
        }
        return myok('下单成功，请等待分配收集员');
    }

    /**
     * 由于收集员修改订单
     * 需要用户进行二次确认
     * @return [type] [description]
     */
    public function confirmorder()
    {
        $data  = input('post.');
        $order = HawaList::get($data['id']);

        if (empty($order) || $order->State == HawaList::STATEDELETE) {
            return myerr('没有找到您需要的订单');
        }
        
        $company = Company::get($order['CompanyId']);
        if($company['UserId']!==Pub::userid()){
            return myerr('没有权限');
        }

        if ($order->State !== HawaList::STATEWAITOK && $order->State !== HawaList::STATETRANSPORT) {
            return myerr('订单状态无法确认');
        }
        if ($order->ConfirmState !== HawaList::CONFRIMBUSS) {
            return myerr('订单状态无法确认');
        }
        $order->State        = HawaList::STATETRANSPORT;
        $order->ConfirmState = HawaList::CONFRIMBUSS + HawaList::CONFRIMHAWA;
        $order->LoadingTime =  date('Y-m-d H:i',time());
        $order->save();
        Sendmessage::Orderhawa(7, $data['id'], $order);
        return myok('订单确认成功');
    }
    /**
     * 图片上传
     * @return [type] [description]
     */
    public function upimg()
    {
        $type = empty(input('type')) ? 'other' : input('type');
        if (!$type == 'hawa' || !$type == 'buss' || !$type == 'acco') {
            $type = 'other';
        }
        try {
            $file = request()->file('img');
        } catch (\Exception $e) {
            return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!is_null($file)) {
            try {
                $save_path = Env::get('root_path') . 'public\\static' . '\\upimg\\hawa\\' . $type . '\\';
                $info      = $file->validate(["size" => 50000000, 'ext' => 'jpg,png,gif'])->rule("date")->move($save_path);
                //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
                $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
                $image->thumb(2000, 2000)->save($save_path . '\\' . $info->getSaveName());
                if ($info) {
//getSaveName();
                    $p = $info->getFilename();
                    return json_encode(['status' => 'ok', 'data' => SERVERURL . 'static/upimg/hawa/' . $type . '/' . date('Ymd', time()) . '/' . $p]);
                } else {
                    return json_encode(['status' => 'error', 'data' => $info->getError()]);
                }
            } catch (\Exception $e) {
                return json_encode(['status' => 'error', 'data' => $e->getMessage()]);
            }

        } else {
            return json_encode(['status' => 'error', 'data' => '没有找到需要上传的图片']);
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
